<?php

namespace App\Models\Back;

use App\Tool\Tool;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Intervention\Image\ImageManager;

class Category extends Model
{
	/*
	 * 设置
	 * @param   $data    array   表单数据数组
	 * return   boot    数据库更新成功返回true否则返回false
	 */
    public function set($data)
    {
    	if (isset($data['id'])) {
    		$fields = self::findOrFail($data['id']);
	    } else {
		    $fields = $this;
	    }
	    unset($data['_token']);
    	foreach ($data as $key => $value) {
    		//处理null
    		if ($value === null) {
			    $fields->$key = '';
		    } else {
			    $fields->$key = $value;
		    }
	    }

	    return $fields->save();
    }


    /*
     * 添加或修改表单验证
     * @param   array   $request    表单数据数组
     * return   mix     验证通过自动返回true，验证失败自动重定向到上一个页面
     */
	public function setValidator($request)
	{

		if (isset($request['id'])) {
			$id = $request['id'];
		} else {
			$id = 0;
		}

		Validator::make($request, [
			'title' => [
				'required',
				'bail',
				Rule::unique('categories')->ignore($id),
				'max:32'
			],
			'image' => [
				'nullable',
				'image',
				'file',
				Rule::dimensions()->maxWidth(1920)->maxHeight(1920),
			],
			'parent_id' => [
				'integer',
				'required'
			],
			'sort_number' => [
				'integer',
				'required'
			],
			'is_used' => [
				'integer',
				'required'
			],
			'id' => [
				'nullable',
				'integer'
			],
			'meta_title' => [
				'nullable',
				'max:32'
			],
			'meta_keyword' => [
				'nullable',
				'max:32'
			],
			'meta_description' => [
				'nullable',
				'max:180'
			],
		])->validate();
	}


	/*
	 * image图片上传
	 * @param   object  $request    请求的数据对象
	 * return   mix     成功返回图片设置的根目录的后的相对路径，失败返回false
	 */
	public function categoryUpload($request)
	{
		//查询是否为更新，是的话就删除老logo
		if (isset($request->id)) {
			//获取
			$fields = self::findOrFail($request->id);
			//删除
			Storage::disk('category')->delete($fields->image);
			Storage::disk('categoryThumb')->delete($fields->image);
		}
		return $request->image->store('', 'category');
	}


	/*
	 * image生成缩略图
	 * @param   string  $path   路径
	 */
	public function categoryThumb ($name)
	{
		//获取image的url
		$path = storage_path(config('tool.back.category.image.path').$name);
		$thumbPath = storage_path(config('tool.back.category.image.thumbPath').$name);

		//实例化图像管理类
		$manager = new ImageManager();
		$manager->make($path)->resize(50, 50)->save($thumbPath);
	}


	/*
     * 删除表单验证
     * @param   array   $request    表单数据数组
     * return   mix     验证通过自动返回true，验证失败自动重定向到上一个页面
     */
	public function deleteValidator($request)
	{
		Validator::make($request, [
			'selected' => [
				'required',
				'array'
			],
			'selected.*' => [
				'integer',
				'min:1'
			]
		])->validate();


	}


	/*
	 * 删除分类，支持批量删除，递归删除
	 * @param   array   $idList 要删除的id列表
	 */
	public function deleteCategory($idList)
	{
		//获取分类list
		$itemList = self::select('id','parent_id', 'image')->get()->toArray();
		//查找选中的分类下的子类id
		$sonIdList = Tool::getSon($idList, $itemList);
		$deleteList = array_unique(array_merge($idList, $sonIdList));

		//删除条目的image
		foreach ($itemList as $item) {
			if (in_array($item['id'], $deleteList)) {
				//删除图片
				Storage::disk('category')->delete($item['image']);
				Storage::disk('categoryThumb')->delete($item['image']);
			}
		}

		//删除数据库信息
		return self::destroy($deleteList);
	}


	/*
	 * 分类排序问题
	 */
	public function categoryOrder($field, $sort)
	{
		$sort = $sort == 'asc' ? $sort : 'desc';
		return json_decode(self::orderBy($field, $sort)->get(),true);
	}


	/*
	 * 返回无限级分类后的分类数组
	 */
	public function getCategoryTree ()
	{
		//获取分类信息，转换成数组
		$collection = Category::select('id','parent_id', 'title')->get()->toArray();
		return Tool::tree($collection);
	}
}
